package com.binarycube.webserver;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
 * Triggers reload of server configuration
 * @author chris
 *
 */

public class RefreshHandler extends AbstractHandler {

	static Logger log = Logger.getLogger(RefreshHandler.class.getName());
	
	WebServer _server;
	
	public RefreshHandler(WebServer server){
		_server = server;
	}
	



	
	@Override
	public void handle(String target, final Request baseRequest,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
	    try {
	    	System.out.println(_server.config.getLoadedTS());
        	_server.reload();
        	System.out.println(_server.config.getLoadedTS());
        	response.getWriter().println("Server configuration refreshed.");
        	response.setStatus(HttpServletResponse.SC_OK);
    		response.flushBuffer();
            baseRequest.setHandled(true);
        } catch (Exception e) {
        	log.error("Error handling page request: ", e);
        	response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Oops, there has been a problem in the server:" + e.getLocalizedMessage());
        } 
		
		
	}
	

	

}

